<script setup>
import { useUserStore } from '@/stores/user';
import { ref } from 'vue';
import { userUpdateService, userUpdatePwdService, userAvatarUpdateService } from '@/apis/user'

const userStore = useUserStore()
const userInfo = ref({ ...userStore.userInfo })
//获取表单实例
const formRef = ref(null)

const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}$/,
      message: '昵称必须是2-10位的非空字符串',
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: confirmPasswordValidator, trigger: 'blur' }
  ]
}
// 确认密码的验证器
function confirmPasswordValidator(rule, value, callback) {
  if (value === passwordInfo.value.new_pwd) {
    callback();
  } else {
    callback(new Error('两次输入的密码不一致'));
  }
}

const updateUserInfo = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await userUpdateService(userInfo.value)
      ElMessage.success('修改成功');
      //修改pinia中的个人信息
      userStore.setInfo(userInfo.value)
    }
  })
}

const passwordInfo = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
});

const showPasswordForm = ref(false);

// 切换修改密码表单的显示状态
const togglePasswordForm = () => {
  showPasswordForm.value = true;
};

const toggleUserForm = () => {
  showPasswordForm.value = false
}

const updatePassword = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await userUpdatePwdService({
        old_pwd: passwordInfo.value.old_pwd,
        new_pwd: passwordInfo.value.new_pwd,
        re_pwd: passwordInfo.value.re_pwd
      })
      ElMessage.success('修改成功');
      //重置表单和隐藏表单
      passwordInfo.value = {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      }
      showPasswordForm.value = false
    }
  })
}
//用户头像地址
const avatarUrl = ref(userStore.userInfo.userPic)
//图片上传成功的回调函数
const uploadSuccess = async (result) => {
  //获取新的url地址
  avatarUrl.value = result.data
  //调用接口修改数据库的url地址
  await userAvatarUpdateService(avatarUrl.value);
  ElMessage.success('修改成功')
  //修改pinia中的数据
  userStore.userInfo.userPic = avatarUrl.value
  //重新获取新数据
  userInfo = ref({ ...userStore.userInfo })
}

</script>

<template>
  <div class="home-overview">
    <!-- 用户信息 -->
    <div class="user-meta">
      <div>
        <el-upload :show-file-list="false" :auto-upload="true" action="/api/upload" name="file"
          :on-success="uploadSuccess">
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
          <img v-else src="@/assets/images/default.jpg" class="avatar" />
        </el-upload>
      </div>
      <h4>{{ userStore.userInfo?.nickname }}</h4>
    </div>
    <div class="item">
      <a href="javascript:;" @click="toggleUserForm">
        <span class="iconfont icon-huiyuan"></span>
        <p>会员中心</p>
      </a>
      <a href="javascript:;" @click="togglePasswordForm">
        <span class="iconfont icon-anquanzhongxin"></span>
        <p>安全设置</p>
      </a>
      <RouterLink to="/member/address"><span class="iconfont icon-dingwei"></span>
        <p>地址管理</p>
      </RouterLink>
    </div>
  </div>
  <div class="like-container">
    <div class="home-panel">
      <div class="header">
        <h4 data-v-bcb266e0="">个人信息</h4>
      </div>
      <el-row>
        <el-col :span="15">
          <el-form :model="userInfo" ref="formRef" v-if="showPasswordForm ? false : true" :rules="rules"
            label-width="100px" size="large">
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="userInfo.nickname"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userInfo.phone"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateUserInfo">保存</el-button>
            </el-form-item>
          </el-form>
          <!-- 修改密码表单，初始时隐藏 -->
          <el-form v-if="showPasswordForm" :model="passwordInfo" ref="formRef" :rules="rules" label-width="100px"
            size="large">
            <el-form-item label="原密码" prop="old_pwd">
              <el-input v-model="passwordInfo.old_pwd" type="text"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new_pwd">
              <el-input v-model="passwordInfo.new_pwd" type="text"></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" prop="re_pwd">
              <el-input v-model="passwordInfo.re_pwd" type="text"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updatePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped lang="scss">
.home-overview {
  height: 132px;
  background: url(@/assets/images/center-bg.png) no-repeat center / cover;
  display: flex;

  .user-meta {
    flex: 1;
    display: flex;
    align-items: center;

    .avatar {
      width: 85px;
      height: 85px;
      border-radius: 50%;
      overflow: hidden;
      margin-left: 60px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    h4 {
      padding-left: 26px;
      font-size: 18px;
      font-weight: normal;
      color: white;
    }
  }

  .item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-around;

    &:first-child {
      border-right: 1px solid #f4f4f4;
    }

    a {
      color: white;
      font-size: 16px;
      text-align: center;

      .iconfont {
        font-size: 32px;
      }

      p {
        line-height: 32px;
      }
    }
  }
}

.like-container {
  margin-top: 20px;
  border-radius: 4px;
  background-color: #fff;
}

.home-panel {
  background-color: #fff;
  padding: 0 20px;
  margin-top: 20px;
  height: 400px;

  .header {
    height: 66px;
    border-bottom: 1px solid #f5f5f5;
    padding: 18px 0;
    display: flex;
    justify-content: space-between;
    align-items: baseline;

    h4 {
      font-size: 22px;
      font-weight: 400;
    }

  }

  .goods-list {
    display: flex;
    justify-content: space-around;
  }
}
</style>